package com.cindata

import com.cindata.dictionary.ImportTypeDict
import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class EstateImportController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService

    @Transactional
    def index(Integer max)
    {
        def order = params["order"]
        def sort = params["sort"]
        params.max = Math.min(max ?: 10, 100)
        def importFileType = ImportTypeDict.findByCode("Estate")

        String sql = " from estateImportBatch e where e.importFileType.id = ${importFileType.id}"
        def user = User.findById(springSecurityService.principal.id)

        def accountSql = Account.FilterAccountSql(user)
        if (accountSql)
        {
            sql += " and e.createBy.account.id in ${accountSql}"
        }

        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += " order by e.batchNumber desc "
        }

        def estateImportList = EstateImport.executeQuery(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        respond EstateImport.list(params), model: [estateImportCount: EstateImport.count(), estateImportBatchList: estateImportList, params: params]
    }

    @Transactional
    def searchImport()
    {
        def order = params["order"]
        def sort = params["sort"]
        // def webUtils = WebUtils.retrieveGrailsWebRequest().getSession()
        def queryParam = new HashMap()
        //押品地址
        def user = User.findById(springSecurityService.principal.id)
        String sql = "from EstateImport e where 1=1  "
        def accountSql = Account.FilterAccountSql(user)
        if (accountSql)
        {
            sql += "and e.createBy.account.id in ${accountSql} "
        }
        if (params["id"])
        {
            def id = Long.parseLong(params["id"])
            sql += "and e.batch.id = :id "
            queryParam["id"] = id
        }
        if (params["batchs"])
        {
            sql += "and e.batch.batchNumber like :batchs "
            queryParam["batchs"] = "%" + params["batchs"] + "%"
        }
        if (params["createBy"])
        {
            sql += "and e.createBy.username = :createBy "
            queryParam["createBy"] = params["createBy"]
        }

        if (params["startDate"] && params["endDate"])
        {
            sql += "and e.startDate between to_date(:startDate,'yyyy年mm月dd日') and to_date(:endDate,'yyyy年mm月dd日') "
            queryParam["startDate"] = params["startDate"]
            queryParam["endDate"] = params["endDate"]
        }
        if (params["status"])
        {
            def status = Long.parseLong(params["status"])
            sql += " and e.estateStatus.id = :status "
            queryParam["status"] = status
        }
        if (params["address"])
        {
            sql += " and e.address like :address "
            queryParam["address"] = "%" + params["address"] + "%"
        }
        //执行查询方法
        def count = EstateImport.executeQuery("select count(e.id) " + sql, queryParam)
        def estateImportList
        if (count[0] > 0)
        {
            params.max = params.max ?: 10
            params.offset = params.offset ?: 0
            if (order && sort)
            {
                sql += " order by e.${sort} ${order}"
            }
            else
            {
                sql += " order by e.externalId desc "
            }
            estateImportList = EstateImport.executeQuery(sql, queryParam, [max: params.max ?: 10, offset: params.offset ?: 0])
        }
        if (estateImportList != null)
        {

            respond EstateImport, model: [estateImportList: estateImportList, estateImportCount: count[0], params: params], view: 'index'
        }
        else
        {
            respond EstateImport, view: 'index'
        }
    }

    def show(EstateImport estateImport)
    {
        respond estateImport
    }

    def create()
    {
        respond new EstateImport(params)
    }

    @Transactional
    def save(EstateImport estateImport)
    {
        if (estateImport == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (estateImport.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond estateImport.errors, view: 'create'
            return
        }

        estateImport.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'estateImport.label', default: 'EstateImport'), estateImport.id])
                redirect estateImport
            }
            '*' { respond estateImport, [status: CREATED] }
        }
    }

    def edit(EstateImport estateImport)
    {
        respond estateImport
    }

    @Transactional
    def update(EstateImport estateImport)
    {
        if (estateImport == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (estateImport.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond estateImport.errors, view: 'edit'
            return
        }

        estateImport.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'estateImport.label', default: 'EstateImport'), estateImport.id])
                redirect estateImport
            }
            '*' { respond estateImport, [status: OK] }
        }
    }

    @Transactional
    def delete(EstateImport estateImport)
    {

        if (estateImport == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        estateImport.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'estateImport.label', default: 'EstateImport'), estateImport.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'estateImport.label', default: 'EstateImport'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }
}
